<?php
abstract class SRActiveRecord extends CActiveRecord {
	private $_pk;								// old primary key value
		
	public function insert($attributes=null)
	{
		if(!$this->getIsNewRecord())
			throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
		if($this->beforeSave())
		{
			Yii::trace(get_class($this).'.insert()','SRActiveRecord');
			$builder=$this->getCommandBuilder();
			$table=$this->getMetaData()->tableSchema;
			
			$this->setAttribute('id', $this->getSequenceId());
			$command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
			if($command->execute())
			{
				$primaryKey=$table->primaryKey;
				if($table->sequenceName!==null)
				{
					if(is_string($primaryKey) && $this->$primaryKey===null)
						
						$this->$primaryKey=$builder->getLastInsertID($table);
					
					
					else if(is_array($primaryKey))
					{
						foreach($primaryKey as $pk)
						{
							if($this->$pk===null)
							{
								$this->$pk=$builder->getLastInsertID($table);
								break;
							}
						}
					}
				}
				$this->_pk=$this->getPrimaryKey();
				$this->afterSave();
				$this->setIsNewRecord(false);
				$this->setScenario('update');
				return true;
			}
		}
		return false;
	}
	
	
	
	
	public function getSequenceId(){
		
		$builder=$this->getCommandBuilder();
		$table=$this->getMetaData()->tableSchema;
		$command=$builder->createSqlCommand('select nextval("sq_my_sequence") as value;');
		$datareader = $command->query();
		return $datareader->readColumn(0);
		
	}
	



	function behaviors() {
		return array(
				'tags' => array(
						'class' => 'ext.yiiext.behaviors.model.taggable.ETaggableBehavior',
						// Table where tags are stored
						'tagTable' => 'Tag',
						// Cross-table that stores tag-model connections.
						// By default it's your_model_tableTag
						'tagBindingTable' => 'TagRecord',
						// Foreign key in cross-table.
						// By default it's your_model_tableId
						'modelTableFk' => 'record_Id',
						// Tag table PK field
						'tagTablePk' => 'id',
						// Tag name field
						'tagTableName' => 'name',
						// Tag counter field
						// if null (default) does not write tag counts to DB
						'tagTableCount' => 'count',
						// Tag binding table tag ID
						'tagBindingTableTagId' => 'tag_id',
						// Caching component ID. If false don't use cache.
						// Defaults to false.
						'cacheID' => 'cache',

						// Save nonexisting tags.
						// When false, throws exception when saving nonexisting tag.
						'createTagsAutomatically' => true,

						// Default tag selection criteria
						

						// Values to insert to tag table on adding tag
						'insertValues' => array(
								'count' => 0,
						),
				)
		);
	}
}